#!/usr/local/env python3
#author:fonzie

import requests
import re
import sys
import traceback
import json
import functools
from config import api_urls, headers
from assist.log_tools import console_out
logs = console_out('per-ip.log')

def log(func):
    print(log.__name__)
    @functools.wraps(func)
    def wapper(*args, **kwargs):
        print(wapper.__name__)
        print(func.__name__)
        print ('开始打印日志')
        try:
            res = func(*args, **kwargs)
            logs.info(res)
        except Exception as e:
            logs.error(e)
            # logs.error(traceback.print_exc())
            logs.error(traceback.format_exc())
            res = e

        return res

        print('不会执行的日志')
    print('开始执行函数%s'%func.__name__)
    return wapper

@log
def check_url(url):
    if not url:
        return False

    url = re.match('((http|https)\\:\\/\\/.*?\\/)', url).group(1)
    req = requests.get(url=url, headers=headers, timeout=5)
    status = (True if req.status_code == 200 else False)

    return status

#国外的IP地址查询库，可能会被屏蔽
def ip_api(ip):
    if not check_url(api_urls.get('ip_api', None)):
        return False
    url = api_urls['ip_api'].format(IP=ip)

    req = requests.get(url=url, headers=headers, timeout=5)
    req_json = req.json()

    return req_json

#淘宝的IP地址查询库，据说不是很准确
def taobao_api(ip):
    if not check_url(api_urls.get('taobao_api', None)):
        return False

    url = api_urls['taobao_api'].format(IP=ip)
    req = requests.get(url=url, headers=headers, timeout=10)
    req_json = json.loads(req.text)

    return req_json

#国外的网站容器被墙
@log
def sudops(ip):
    if not check_url(api_urls.get('sudops', None)):
        return False
    url = api_urls.get('sudops', None)


    url = url.format(IP=ip)
    req = requests.get(url=url, headers=headers, timeout=10)
    req_json = req.json()


    return req_json



if __name__ == "__main__":
    #pass
    # ip_api('114.114.114.114')
    # taobao_api('114.114.114.114')
    print(sudops('114.114.114.114'))